package net.dp.global;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.log4j.Logger;

public class GlobalConfig {

	private static Logger logger = Logger.getLogger(GlobalConfig.class);

	private static Lock lock = new ReentrantLock();

	/**
	 * 存储全局配置项
	 */
	private static Map<String, String> map = new HashMap<String, String>();

	public static String getConfig(String key) {
		if (map.containsKey(key)) {
			return map.get(key);
		}
		return null;
	}

	public static String getConfig(String key, String defaultValue) {
		if (map.containsKey(key)) {
			return map.get(key);
		} else {
			return defaultValue;
		}
	}

	public static void loadConfig() {

		logger.debug("start load config...");

		// 读配置项: 配置文件/数据库
		List<ConfigInfo> configs = new ArrayList<ConfigInfo>();

		for (ConfigInfo info : configs) {
			// TODO should check configName
			map.put(info.getConfigName(), info.getConfigValue());
			logger.debug(info);
		}

		logger.debug("end load config...");
	}

	public static void refreshConfig() {
		try {
			lock.lock();

			logger.debug("refresh config...");

			// TODO 读配置项: 配置文件/数据库
			List<ConfigInfo> configs = new ArrayList<ConfigInfo>();

			HashMap<String, String> temp = new HashMap<String, String>();
			for (ConfigInfo info : configs) {
				// TODO should check configName
				temp.put(info.getConfigName(), info.getConfigValue());
				logger.debug(info);
			}

			map.clear();
			map.putAll(temp);

			logger.debug("refresh end...");

		} finally {
			lock.unlock();
		}
	}
}

class ConfigInfo {

	private String configName;
	private String configValue;
	private String configRegex;
	private String configDesc;
	private String configDate;

	public String getConfigName() {
		return configName;
	}

	public void setConfigName(String configName) {
		this.configName = configName;
	}

	public String getConfigValue() {
		return configValue;
	}

	public void setConfigValue(String configValue) {
		this.configValue = configValue;
	}

	public String getConfigRegex() {
		return configRegex;
	}

	public void setConfigRegex(String configRegex) {
		this.configRegex = configRegex;
	}

	public String getConfigDesc() {
		return configDesc;
	}

	public void setConfigDesc(String configDesc) {
		this.configDesc = configDesc;
	}

	public String getConfigDate() {
		return configDate;
	}

	public void setConfigDate(String configDate) {
		this.configDate = configDate;
	}

	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		sb.append(configName);
		sb.append(System.getProperty(GlobalConstant.LINE_SEPARATOR));
		sb.append(configValue);
		sb.append(System.getProperty(GlobalConstant.LINE_SEPARATOR));
		return sb.toString();
	}
}